package image

import (
	"errors"
	"github.com/nfnt/resize"
	"image"
	"image/draw"
	"micro-grpc-server/library/image/handlers"
)

type Canvas struct {
	Path     string // 图片路径
	Width    int    // 宽度
	Height   int    // 高度
	Color    string // 底色 Color 与 Path 只会生效一个
	FontFile string // 字体文件
}

func (b *Canvas) GenerateDrawCanvas() (*image.RGBA, error) {
	if len(b.Path) == 0 {
		return b.createColorBackground()
	}
	return b.createImageBackground()
}

func (b *Canvas) createImageBackground() (*image.RGBA, error) {
	var (
		img image.Image
		err error
	)
	img, err = handlers.LoadImage(b.Path)
	if err != nil {
		return nil, errors.New("load image " + b.Path + " failed. " + err.Error())
	}
	if b.Width > 0 || b.Height > 0 {
		img = resize.Resize(uint(b.Width), uint(b.Height), img, resize.Lanczos3)
	} else {
		b.Height, b.Width = handlers.LoadImageSize(img)
	}

	newImg := image.NewRGBA(image.Rect(0, 0, b.Width, b.Height))
	draw.Draw(newImg, newImg.Bounds(), img, img.Bounds().Min, draw.Src)

	return newImg, nil
}

func (b *Canvas) createColorBackground() (img *image.RGBA, err error) {
	var (
		height, width = b.Height, b.Width
	)

	img = image.NewRGBA(image.Rect(0, 0, width, height))
	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			//if x%8 == 0 {
			img.Set(x, y, handlers.RGBAColor(b.Color))
			//img.Set(x, y, color.RGBA{R: uint8(x % 256), G: uint8(y % 256), B: 0, A: 255})
			//}
		}
	}

	return
}
